package io.guanghe.common.xss;

import com.google.common.base.CaseFormat;
import org.apache.commons.lang3.StringUtils;

/**
 * SQL过滤
 */
public class SQLFilter {

    //分页SQL注入过滤
    public static String sqlInject(String str) {
        str = filter(str);
        //驼峰转下划线
        return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, str);
    }

    //过滤
    public static String filter(String str){
        if (StringUtils.isBlank(str)) {
            return "";
        }
        //去掉'|"|;|\字符
        str = StringUtils.replace(str, "'", "");
        str = StringUtils.replace(str, "\"", "");
        str = StringUtils.replace(str, ";", "");
        str = StringUtils.replace(str, "\\", "");

        //转换成小写
        String testStr = str.toLowerCase();

        //非法字符
        String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop"};

        //判断是否包含非法字符
        for (String keyword : keywords) {
            if (testStr.indexOf(keyword) != -1) {
                throw new RuntimeException("请求包含SQL攻击非法字符！");
            }
        }
        return str;
    }
}
